﻿using System;
using System.Collections.Concurrent;
namespace Scorpio.Tools {
    internal class ScorpioArrayPool<T> {
#if SCORPIO_POOL
        private static ConcurrentQueue<T[]> queueArray4 = new ConcurrentQueue<T[]>();
        private static ConcurrentQueue<T[]> queueArray8 = new ConcurrentQueue<T[]>();
        private static ConcurrentQueue<T[]> queueArray16 = new ConcurrentQueue<T[]>();
        private static ConcurrentQueue<T[]> queueArray32 = new ConcurrentQueue<T[]>();
        private static ConcurrentQueue<T[]> queueArray64 = new ConcurrentQueue<T[]>();
        private static ConcurrentQueue<T[]> GetQueue(int length) {
            switch (length) {
                case 4: return queueArray4;
                case 8: return queueArray8;
                case 16: return queueArray16;
                case 32: return queueArray32;
                case 64: return queueArray64;
                default: return null;
            }
        }
        public static T[] Create(int length) {
            var queue = GetQueue(length);
            if (queue != null && queue.Count > 0 && queue.TryDequeue(out var result)) {
                return result;
            }
            return new T[length];
        }
        public static void Free(T[] array) {
            if (array.Length == 0) return;
            var queue = GetQueue(array.Length);
            if (queue != null) {
                Array.Clear(array, 0, array.Length);
                queue.Enqueue(array);
            }
        }
#else
        public static T[] Create(int length) => new T[length];
        public static void Free(T[] array) { }
#endif
    }
}
